<script setup lang="ts">
import { NButton } from 'naive-ui'
import type { FormConfigSubset } from '../shared'
import { cloneDeep } from 'lodash-es'

const props = defineProps<{
  subset: FormConfigSubset
  data: Record<string, any>
}>()

const emit = defineEmits<{
  (event: 'add:subItem', k: string): void
  (event: 'delete:subItem', k: string, index: number): void
}>()

const handleAdd = (k: string) => emit('add:subItem', k)
const handleDelete = (k: string, i: number) => emit('delete:subItem', k, i)

const subItems = (k: string) => props.data[k]
const subItemConfigs = (k: string, i: number) => {
  const configs = cloneDeep(props.subset[k])

  configs.forEach((element, ii) => {
    const elementKey = element.formItemProps?.path!
    const path = `${k}[${i}].${elementKey}`
    const json = JSON.parse(JSON.stringify(element).replace(new RegExp(`${elementKey}`, 'g'), path))
    element.formItemProps!.path = path
    configs[ii] = json
  })
  return configs
}
</script>

<template>
  <div class="dynamic-form-item-subset">
    <div
      v-for="(v, k) in subset"
      :key="k"
      class="dfis"
    >
      <NButton
        type="primary"
        ghost
        @click="handleAdd(k)"
      >
        添加
      </NButton>
      <slot
        :value="v"
        :key="k"
      ></slot>

      <div
        v-for="(e, i) in subItems(k)"
        :key="i"
        class="dfis-item"
      >
        <NButton
          type="error"
          ghost
          @click="handleDelete(k, i)"
        >
          删除
        </NButton>
        <slot
          name="subItems"
          :elements="subItemConfigs(k, i)"
        ></slot>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dfis .n-button {
  margin-bottom: 8px;
}

.dfis .dfis-item {
  margin: 8px 0;
}
</style>
